package com.yang.leather.common.upload;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.yang.leather.admin.pojo.ImgsDel;
import com.yang.leather.common.store.IImgsDelService;
import com.yang.leather.common.upload.UploadRule.UploadFile;
import com.yang.leather.common.util.ComUtils;
import com.yang.leather.core.SpringContextHolder;

public class UploadFileListerner implements HttpSessionListener {
	
	public void sessionCreated(HttpSessionEvent se) {
	}

	@SuppressWarnings("unchecked")
	public void sessionDestroyed(HttpSessionEvent se) {
		IImgsDelService imgsDelService = SpringContextHolder.getBean("admin/imgsDelService",IImgsDelService.class);
		
		// 清理上传文件
		HttpSession session = se.getSession();
		Enumeration<String> em = session.getAttributeNames();
		List<UploadFile> list = new ArrayList<UploadFile>();
		while (em.hasMoreElements()) {
			Object o = session.getAttribute(em.nextElement());
			if (o instanceof UploadRule) {
				UploadRule ur = (UploadRule) o;
				if(ur.getUploadFiles()!=null){
					list.addAll(ur.getUploadFiles());
				}
			}
		}
		if(list.size()>0){
			List<ImgsDel> imgDels = new ArrayList<ImgsDel>();
			for(UploadFile file : list){
				ImgsDel del = new ImgsDel();
				del.setFilePath(file.getFilePath());
				del.setFileName(file.getFileName());
				del.setCreateDate(ComUtils.now());
				imgDels.add(del);
			}
			imgsDelService.batchSave(imgDels);
		}
	}
}